<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午12:03
 *
 * 购物车类
 */

use LaravelBook\Ardent\Ardent;

class Order extends Ardent{

    public $fillable=['status'];
    public static $relationsData = array(
        'member' => array(self::BELONGS_TO, 'Member', 'foreignKey' => 'member_id', 'otherKey' => 'id'),
        'orderFoods' => array(self::HAS_MANY, 'OrderFood', 'foreignKey' => 'order_id', 'otherKey' => 'id'),
    );


    const GOT_ORDER = 'GOT_ORDER';
    const GOT_PICKET = 'GOT_PICKET';
    const SETTLED = 'SETTLED';
    const CLOSE = 'CLOSE';

    const PAY_TYPE_NULL     = 0;//未支付
    const PAY_TYPE_ALIPAY   = 1;//支付宝
    const PAY_TYPE_WECHAT   = 2;//微信
    const PAY_TYPE_SCHOOL   = 3;//校园卡

    public static $statuses = array(
        array('id' => 0,'keyword'=>'GOT_ORDER',   'display_name'=>'已下单'),
        array('id' => 1,'keyword'=>'GOT_PICKET', 'display_name'=>'已打票'),
        array('id' => 2,'keyword'=>'SETTLED',     'display_name'=>'已结算'),
        array('id' => 3,'keyword'=>'WAIT_DISH',     'display_name'=>'等待出菜'),
        array('id' => 4,'keyword'=>'DISHED',     'display_name'=>'已出菜'),
        array('id' => 5,'keyword'=>'CLOSE',     'display_name'=>'关闭'),
    );

    const ORDER_TYPE_XIADAN = 0;//:已下单，
    const ORDER_TYPE_JIESUAN = 2;//:已结算,
    const ORDER_TYPE_DAPIAO  = 1;//:已打票，
    const ORDER_TYPE_DENGDAICHUCAI = 3;//等待出菜,
    const ORDER_TYPE_YICHUCAI = 4;// 已经出菜

    public static $paymentTypes = [
        ['id'=>0,'keyword'=>'PAY_TYPE_NULL','display_name'=>'未支付'],
        ['id'=>1,'keyword'=>'PAY_TYPE_ALIPAY','display_name'=>'支付宝'],
        ['id'=>2,'keyword'=>'PAY_TYPE_WECHAT','display_name'=>'微信'],
        ['id'=>3,'keyword'=>'PAY_TYPE_SCHOOL','display_name'=>'校园卡']
    ];


    public static $column = array(
        'member_id' => '用户昵称',
        'total_price' => '总价',
        'status' => '状态',
        'created_at' => '创建时间',
        'payment_type'=>'支付方式',
    );

    public static function getStatusIDByKeyword($keyword){
        foreach(self::$statuses as $status){
            if($status['keyword'] == $keyword){
                return $status['id'];
            }
        }
        return false;
    }
    public static function getStatusNameByID($id){
        foreach(self::$statuses as $status){
            if($status['id'] == $id){
                return $status['display_name'];
            }
        }
        return false;
    }


    public function beforeDelete( $forced = false )
    {
        try {
            DB::table('order_foods')->where('order_id', $this->id)->delete();
        } catch(Execption $e) {
            $this->errors()->add('error', $e->getMessage());
            return false;
        }

        return true;
    }

    public function createOrder($member_id, $foodIds, $counts, $totalPrice){
        DB::beginTransaction();
        $foods = Food::whereIn('id', $foodIds)->lockForUpdate()->get();
        if(!$foods){
            $this->errors()->add('error','餐盘中没有任何餐品，无法生成空订单！');
            DB::rollback();
            return false;
        }
        $this->member_id = $member_id;
        $this->status = Order::ORDER_TYPE_XIADAN;
        $this->total_price = $totalPrice;
        if(!$this->save()){
            DB::rollback();
            $this->errors()->add('error','生成订单失败，请重新提交订单！！！');
            return false;
        }
        $i = 0;
        foreach($foods as $food){
            $orderFood = new OrderFood();
            if(isset($food) && $food){
                if($food->count < $counts[$i]){
                    DB::rollback();
                    $this->errors()->add('error','菜单：'.$food->name."的库存已不足，请重新更换菜品提交订单！");
                    return false;
                }
                $orderFood->order_id = $this->id;
                $orderFood->name = $food->name;
                $orderFood->is_package = $food->is_package;
                $orderFood->original_price = $food->original_price;
                $orderFood->price = $food->price;
                $orderFood->count = $counts[$i];
                $orderFood->description = $food->description;
                if(!$orderFood->save()){
                    DB::rollback();
                    $this->errors()->add('error',"保存订单详情失败，请重新提交订单");
                    return false;
                }

                $food->count = bcsub($food->count,$counts[$i]);
                if(!$food->save()){
                    DB::rollback();
                    $this->errors()->add('error',"保存菜品库存失败，请重新提交订单");
                    return false;
                }

                //保存相册
                $orderFood->saveThumb($food->thumbs);
            }
            $i++;
        }
        DB::commit();
        return true;
    }

    public function setPaymentTypes($type){
        if(!in_array($type,[0,1,2,3])){
            return false;
        }
        $this->payment_type = $type;
        $res=$this->save();
        return $res;
    }
    public function getIntegralPrice(){
        return $this->total_price * Setting::getInstance()->integral_pay_scale;
    }

    public function getQRCode(){
        $timestamp = strtotime($this->created_at);
        $tmpStr = $this->getSignature($timestamp, $this->id);

        return DNS2D :: getBarcodeHtml ($this->id, "QRCODE" , 7 , 7 , "black" ) ;
    }

    public function setStatus($keyword = self::GOT_ORDER){
        $this->status = self::getStatusIDByKeyword($keyword);
        $res=$this->save();
        if($this->status == Order::ORDER_TYPE_JIESUAN){
            $input=array('order_id'=>$this->id,'status'=>'1');
            $today=OrderToday::where('order_id',$this->id)->first();
            if($today){
                $today->update($input);
            }else{
               OrderToday::create($input);
            }
            $this->status=Order::ORDER_TYPE_DENGDAICHUCAI;
            $this->save();

        }
        return $res;
    }

    public function getPicket(){
        $foods = array();
        $food = array();
        $total_price = 0;
        foreach($this->orderFoods as $orderFood){
            $food['name'] = $orderFood->name;
            $food['price'] = number_format($orderFood->price,2);
            $food['count'] = $orderFood->count;
            $food['money'] = number_format($orderFood->price*$orderFood->count,2);
            array_push($foods, $food);
            $total_price += $food['money'];
        }
        return $this->generatePicket($foods, $total_price);
    }

    private function generatePicket($foods, $total_price){
        $picket = new stdClass;
        $picket->errmsg = 'ok';
        $picket->header_title = '欢迎光临';
        $picket->name = '华侨大学餐厅';
        $picket->footer_title = '谢谢惠顾';
        $picket->order_id=$this->id;
        $orderToday=OrderToday::where('order_id',$this->id)->first();
        if(!$orderToday){
            $this->errors()->add('error',"订单id:{$this->id},不是今天的订单，不允许打印");
            return false;
        }
        $picket->queue_num=isset($orderToday)?$orderToday->id:"-1";
        $picket->queue_id = isset($orderToday) ? $orderToday->id % 999 : "-1";
        $wait_number=self::getWaitNumber();
        $picket->wait_num=$wait_number;
        $picket->total_price = number_format($total_price,2).'元';
        $picket->foods = $foods;
        $picket->status = self::$statuses[$this->status]['keyword']; //GOT_ORDER 或 SETTLED

        return $picket;
    }

    public function checkSignature($checksum, $timestamp){
        return $checksum == $this->getChecksum($timestamp);
    }

    public function getChecksum($timestamp){
        return $this->getSignature($timestamp);
    }

    private function getSignature($timestamp){
        $tmpStr = md5($timestamp).$this->id;
        return sha1( $tmpStr );
    }

    /**
     * 获取等待人数
     * @return int|string
     */
    public function getWaitNumber()
    {
        $num=OrderToday::where('status',1)
            ->where('updated_at','>=',date('Y-m-d 00:00:00',time()))
            ->where('updated_at','<=',date('Y-m-d 23:59:59',time()))
            ->count('id');
        return $num?$num:0;
    }

}
